package com.wing.device.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.graphbuilder.math.func.MinFunction;
import com.wing.common.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.web.db.config.util.DynamicDataSource;
import com.wing.device.model.entity.DeviceCategory;
import com.wing.device.model.entity.DeviceType;
import com.wing.device.model.request.DeviceTypeForm;
import com.wing.device.model.response.TreeDataVo;
import com.wing.device.service.DeviceTypeService;
import com.wing.product.model.entity.Product;
import com.wing.product.model.entity.ProductType;
import com.wing.product.model.request.ProductTypeForm;
import com.wing.product.service.ProductTypeService;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.*;
import java.util.stream.Collectors;


/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-设备类型管理", tags = "#/device/deviceType")
@RestController("deviceTypeController")
@RequestMapping("device/admin/deviceType")
public class DeviceTypeController {

    @Autowired
    private DeviceTypeService deviceTypeService;

    @Autowired
    private ProductTypeService productTypeService;



    @ApiOperation(value = "查询所有设备类型", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "code", value = "编号", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<DeviceType> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String name
            ,String code
            ,Long id
    ){

        Page<DeviceType> pg = new Page<>(page, limit);
        QueryWrapper<DeviceType> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }

        //搜索
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.like("code", code);
        }
        if (id!=null){
            queryWrapper.eq("id",id);
        }
        IPage<DeviceType> list = deviceTypeService.getBaseMapper().selectPage(pg, queryWrapper);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "查询所有设备分类", notes = "添加")
    @GetMapping("/getAllType")
    public JsonResult getAllType(){

        List<DeviceType> list = deviceTypeService.list();
        return JsonResult.success(list);
    }

    @ApiOperation(value = "获取下一个code", notes = "添加")
    @GetMapping("/getNextCode")
    public JsonResult getNextCode(){
        String code = deviceTypeService.getCode();
        return JsonResult.success(code);
    }

    @ApiOperation(value = "查询所有物资归于资产类别的分类", notes = "添加/修改")
    @GetMapping("/getAllTypeOnlyPro")
    public JsonResult getAllTypeOnlyPro(){

        QueryWrapper<ProductType> wrapper = new QueryWrapper<>();
        wrapper.eq("material_nature",3);
        List<ProductType> list = productTypeService.list(wrapper);
        //根据id分组
        Map<Long, List<ProductType>> collect = list.stream().collect(Collectors.groupingBy(ProductType::getParentId));

        List<TreeDataVo> treeDataVos = new ArrayList<>();
        collect.forEach((key, value) -> {
            if (key == -1L) {
                //跟节点
                if (!CollectionUtil.isEmpty(value)) {
                    value.forEach(info -> {
                        TreeDataVo treeDataVo = new TreeDataVo();
                        BeanUtil.copyProperties(info, treeDataVo);
                        treeDataVo.setValue(info.getId().toString());
                        treeDataVo.setCode(info.getId().toString());
                        //设置子集
                        treeDataVo.setChildren(getChildren(info.getId(), collect));
                        treeDataVos.add(treeDataVo);
                    });
                }
            }
        });
        return JsonResult.success(treeDataVos);
    }

    /**
     * 递归获取子集
     * @param id
     * @param collect
     * @return
     */
    private List<TreeDataVo> getChildren(Long id, Map<Long, List<ProductType>> collect) {
        //获取子集
        List<ProductType> list = collect.get(id);
        List<TreeDataVo> treeDataVos = list.stream().map(info -> {
            //迭代转换子集
            TreeDataVo treeDataVo = new TreeDataVo();
            BeanUtil.copyProperties(info, treeDataVo);
            treeDataVo.setValue(info.getId().toString());
            treeDataVo.setCode(info.getId().toString());
            if (haveChildren(info.getId(),collect)){
                treeDataVo.setChildren(getChildren(info.getId(), collect));
            }
            return treeDataVo;
        }).collect(Collectors.toList());
        return treeDataVos;
    }

    /***
     * 判断是否有子集
     * @param id
     * @param collect
     * @return
     */
    private boolean haveChildren(Long id, Map<Long, List<ProductType>> collect) {
        if (CollectionUtil.isEmpty(collect.get(id))){
            return false;
        }else{
            return true;
        }
    }


    @ApiOperation(value = "添加设备类型", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(DeviceTypeForm.Add.class) DeviceTypeForm deviceTypeForm) {

        if (deviceTypeService.add(deviceTypeForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }






    @ApiOperation(value = "修改设备类型", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(DeviceTypeForm.Update.class) DeviceTypeForm deviceTypeForm) {

        DeviceType deviceType = deviceTypeService.getById(deviceTypeForm.getId());
        if(deviceType == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(DeviceType.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(deviceTypeForm, deviceType, copyOptions);
        if (deviceTypeService.updateById(deviceType)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除设备类型", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceTypeId", value = "设备类型id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long deviceTypeId) {

        if (deviceTypeService.removeById(deviceTypeId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "启用设备类型", notes = "启用")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/enable")
    public JsonResult enable(@Validated(ProductTypeForm.Add.class) DeviceTypeForm typeForm) {

        DeviceType type=new DeviceType();
        type.setId(typeForm.getId());
        type.setIsDeleted(true);
        if (deviceTypeService.updateById(type)) {
            return JsonResult.success("启用成功");
        }
        return JsonResult.fail("启用失败");
    }

    @ApiOperation(value = "停用设备类型", notes = "停用")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/disable")
    public JsonResult disable(@Validated(ProductTypeForm.Add.class) DeviceTypeForm typeForm) {

        DeviceType tType=new DeviceType();
        tType.setId(typeForm.getId());
        tType.setIsDeleted(false);
        if (deviceTypeService.updateById(tType)) {
            return JsonResult.success("停用成功");
        }
        return JsonResult.fail("停用失败");
    }
}
